package com.mavenq.fly.business.flow.task;

import com.mavenq.fly.business.flow.constant.FlowConstant;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.client.ExternalTaskClient;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
//@Component
public class ShoppingTask {

    private ExternalTaskClient client = null;

    private ExternalTaskClient getClient() {
        if (client == null) {
            client = ExternalTaskClient.create().baseUrl(FlowConstant.BASE_URL).asyncResponseTimeout(10000).build();
        }
        return client;
    }

    @PostConstruct
    private void addShoppingCart() {
        log.info("addShoppingCart started ...");
        getClient().subscribe(FlowConstant.ADD_SHOPPING_CART)
                .processDefinitionKey(FlowConstant.SHOPPING_PROCESS_DEFINITION_KEY)
                .lockDuration(2000)
                .handler(((externalTask, externalTaskService) -> {
                    log.info("addShoppingCart订阅到加入购物车任务");
                    VariableMap variableMap = Variables.createVariables()
                            .putValue("size", "xl")
                            .putValue("toWhere", "北京")
                            .putValue("count", 2);
                    externalTaskService.complete(externalTask, variableMap);
                }))
                .open();
    }


    @PostConstruct
    private void payDelivery() {
        log.info("payDelivery started ...");
        getClient().subscribe(FlowConstant.PAY)
                .processDefinitionKey(FlowConstant.SHOPPING_PROCESS_DEFINITION_KEY)
                .lockDuration(2000)
                .handler(((externalTask, externalTaskService) -> {
                    Object toWhere = externalTask.getVariable("toWhere");
                    log.info("payDelivery,支付完成，收到发货任务, 目的地: {}", String.valueOf(toWhere));
                    externalTaskService.complete(externalTask);
                }))
                .open();
    }



}
